//    Copyright (C) Kherty.  All rights reserved.
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Media;

namespace OpenLS.Spreadsheet
{
    static class TextMetrics
    {
        public static double GetFontHeight(Typeface tf, double FontSize)
        {
            double result;
            ValuePair<Typeface, double> pair = new ValuePair<Typeface, double>(tf, FontSize);
            if (cache.TryGetValue(pair, out result))

                return result;
            FormattedText t = new FormattedText("W",
                    CultureInfo.CurrentCulture, FlowDirection.LeftToRight, tf, PointsToPixelConverter.ToPixel(FontSize), Brushes.Black);
            result = t.Height;
            cache.Add(pair, result);
            return result;

        }
        static readonly Dictionary<ValuePair<Typeface, double>, double> cache = new Dictionary<ValuePair<Typeface, double>, double>(new TypeFaceComparer());

        class TypeFaceComparer : IEqualityComparer<ValuePair<Typeface, double>>
        {
            #region IEqualityComparer<ValuePair<Typeface, double>> Members

            public bool Equals(ValuePair<Typeface, double> x, ValuePair<Typeface, double> y)
            {
                return x.Second == y.Second &&
                    x.First.FontFamily == y.First.FontFamily &&
                    x.First.Stretch == y.First.Stretch &&
                    x.First.Style == y.First.Style &&
                    x.First.Weight == y.First.Weight;
            }

            public int GetHashCode(ValuePair<Typeface, double> obj)
            {
                return obj.Second.GetHashCode() + obj.First.FontFamily.Source.GetHashCode() +
                    obj.First.Stretch.GetHashCode() + obj.First.Style.GetHashCode() + obj.First.Weight.GetHashCode();
            }

            #endregion
        }
        class ValuePair<T1, T2>
        {
            public ValuePair(T1 first, T2 second)
            {
                this.first = first;
                this.second = second;
            }
            private readonly T1 first;

            public T1 First
            {
                get { return first; }
            }
            private readonly T2 second;

            public T2 Second
            {
                get { return second; }
            }


        }
}
}
